package com.lyhlmj.oop_client.Threads;

import com.lyhlmj.oop_client.ClientOperation.ClientUtil.Client;
import com.lyhlmj.oop_client.Frames.PlayFrame.Panels.ChatRoomPanel;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.swing.*;

/* 从服务器获取最新的消息，显示到聊天室窗口
 */
public class GetChatInfoTask extends Thread {
    private Client client = Client.client;
    private ChatRoomPanel chatRoomPanel;

    boolean quitFlag = false;  //终止标识符，为true时循环终止

    public GetChatInfoTask(ChatRoomPanel chatRoomPanel) {
        this.chatRoomPanel = chatRoomPanel;
    }

    //用来终止当前进程
    public void doStop() {
        quitFlag = true;
        System.out.println(" ** 关闭获取聊天内容的线程");
        this.interrupt(); // 让  sleep() 立即中止
        try {
            this.join(); // 等待本线程结束后再退出
        } catch (Exception e) {
        }
    }

    public void run() {
        while (!quitFlag) {
            // 心跳的间隔时间，要和后台的反空闲机制对应
            try {
                sleep(200);  //每0.2s去后端查询一次聊天内容
            } catch (Exception e) {
            }

            try {
                getMessage();
            } catch (Exception e) {
                e.printStackTrace();
                break;  //发送请求错误
            }
        }
    }

    private void getMessage() throws Exception {
        JSONObject jsonReq = new JSONObject();
        JSONObject args = new JSONObject();

        args.put("from", client.getUsername());
        if (client.getPlayers() != null) {
//            args.put("to", "limeijie");
            args.put("to", getOtherUser(client.getUsername()));
        }

        jsonReq.put("cmd", "getMessage");
        jsonReq.put("args", args);

        // send()方法是线程安全的，它使用了互斥锁
        JSONObject jsonResp = client.send(jsonReq);
        int status = -1;
        String reason = null;
        if (jsonResp != null) {
            status = jsonResp.getInt("status");
            reason = jsonResp.optString("reason", "");
//            如果当前data中包含数据，则清空聊天框，否则不刷新
            if (jsonResp.getJSONArray("data") != null && jsonResp.getJSONArray("data").length() != 0) {
                chatRoomPanel.getMsgBox().clear();
            }
        }

        if (status == 0) {
            JSONArray jsonData = jsonResp.getJSONArray("data");
            for (int i = 0; i < jsonData.length(); i++) {
                JSONObject msg = jsonData.getJSONObject(i);
                showMessage(msg);
            }
        }
    }

    private void showMessage(JSONObject msg) {
        SwingUtilities.invokeLater(() -> {
            chatRoomPanel.getMsgBox().appendMessage(msg);
        });
    }

    private String getOtherUser(String username) {
        if (client.getPlayers()[0].equals(username)) {
            return client.getPlayers()[1];
        } else {
            return client.getPlayers()[0];
        }
    }
}
